package com.xcu.mybatis.sqlsession.defaulte;

import com.xcu.mybatis.cfg.Configuration;
import com.xcu.mybatis.sqlsession.SqlSession;
import com.xcu.mybatis.sqlsession.proxy.Mapperproxy;
import com.xcu.mybatis.utils.DataSourceUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

public class DefaultSqlSession implements SqlSession {
    private Connection connection;
    private Configuration cfg;

    public DefaultSqlSession(Configuration cfg){
        this.cfg = cfg;
        this.connection = DataSourceUtil.getConnection(cfg);
    }


    @Override
    public <T> T getMapper(Class<T> daoInterfaceClass) {
       return  (T)Proxy.newProxyInstance(daoInterfaceClass.getClassLoader(),new Class[]{daoInterfaceClass},new Mapperproxy(cfg.getMappers(),connection));
    }

    @Override
    public void close() {
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }
}
